package main

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/logs"
)

var (
	appConf *Config
)

type Config struct {
	logLevel    string
	logPath     string
	collectconf []CollectConf
}
type CollectConf struct {
	logPath string
	topic   string
}

func loadConf(conftype, fileName string) (err error) {
	conf, err := config.NewConfig(conftype, fileName)
	if err != nil {
		fmt.Print(err)
		return
	}
	appConf = &Config{}
	appConf.logLevel = conf.String("logs::log_level")
	if len(appConf.logLevel) == 0 {
		appConf.logLevel = "debug"
	}
	appConf.logPath = conf.String("logs::log_path")
	if len(appConf.logPath) == 0 {
		appConf.logPath = "./log"
	}

	err = loadCollectConf(conf)
	if err != nil {
		fmt.Print(err)
		return
	}
	return
}

func loadCollectConf(conf config.Configer) (err error) {
	var cc CollectConf
	cc.logPath = conf.String("collect::log_path")
	if len(cc.logPath) == 0 {
		cc.logPath = "./log"
	}
	cc.logPath = conf.String("collect::topic")
	if len(cc.topic) == 0 {
		cc.topic = "./log"
	}
	appConf.collectconf = append(appConf.collectconf, cc)
	return
}

func convertLogLevel(level string) int {
	switch level {
	case "debug":
		return logs.LevelDebug
	case "warn":
		return logs.LevelWarn
	case "info":
		return logs.LevelInfo
	case "trace":
		return logs.LevelTrace
	}
	return logs.LevelDebug
}

func initLogger() (err error) {
	cc := make(map[string]interface{})

	cc["fileName"] = appConf.logPath
	cc["level"] = convertLogLevel(appConf.logLevel)
	confstr, err := json.Marshal(cc)
	if err != nil {
		fmt.Print(err)
		return
	}
	err = logs.SetLogger(logs.AdapterFile, string(confstr))
	if err != nil {
		fmt.Print(err)
		return
	}

	return
}
